package com.CST.service.impl.cb;

import com.CST.common.api.Response;
import com.CST.common.constant.Constants;
import com.CST.entity.cb.BdDepartment;
import com.CST.entity.cb.BdEnumdetail;
import com.CST.entity.cb.BdOrganization;
import com.CST.mapper.dataplatform.BdDepartmentMapper;
import com.CST.service.cb.IBdDepartmentService;
import com.CST.service.cb.IBdEnumdetailService;
import com.CST.service.cb.IBdOrganizationService;
import com.CST.util.HttpUtil;
import com.CST.vo.cb.BdDepartmentVO;
import com.CST.vo.cb.BdSysUserDeptCodeVO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 核算科室 服务实现类
 * </p>
 *
 * @author ly
 * @since 2021-09-23
 */
@Service
public class BdDepartmentServiceImpl extends ServiceImpl<BdDepartmentMapper, BdDepartment> implements IBdDepartmentService {

    @Autowired
    private IBdEnumdetailService enumdetailService;

    @Autowired
    private IBdOrganizationService organizationService;


    @Override
    public List<BdDepartment> getDepartmentSource(BdDepartment entity) {
        return baseMapper.getDepartmentSource(entity);
    }

//    @Override
//    public List<BdDepartment> getDepartmentSourceWithOrganization(BdDepartment entity) {
//        List<BdDepartment> resultList = new ArrayList<>();
//        //查询所有的科室部门信息
//        List<BdDepartment> departmentList = baseMapper.getDepartmentSource(entity);
//        List<BdDepartment> PDeptList = departmentList.stream().filter(t -> t.getParentCode().equals("1")).collect(Collectors.toList());
//        List<BdDepartment> DeptList = departmentList.stream().filter(t -> t.getParentCode().equals("0")).collect(Collectors.toList());
//
//        //获取当前默认的组织关系
//        List<BdOrganization> organizationList = getOrganizationRelation(entity);
//        List<String> orgDeptCodeList = organizationList.stream().map(t -> t.getDeptCode()).collect(Collectors.toList());
//        List<BdDepartment> noRelationDeptList = DeptList.stream().filter(t -> !orgDeptCodeList.contains(t.getDeptCode())).collect(Collectors.toList());
//        PDeptList.forEach(item -> {
//            resultList.add(item);
//            List<BdOrganization> matchOrgList = organizationList.stream().filter(t -> t.getPDeptCode().equals(item.getDeptCode())).collect(Collectors.toList());
//            if (CollectionUtils.isNotEmpty(matchOrgList)) {
//                List<String> deptCodeList = matchOrgList.stream().map(t -> t.getDeptCode()).collect(Collectors.toList());
//                List<BdDepartment> matchDeptList = DeptList.stream().filter(t -> deptCodeList.contains(t.getDeptCode())).collect(Collectors.toList());
//                matchDeptList.forEach(ditem -> {
//
//                    ditem.setDeptName(String.join("", "&nbsp;&nbsp;&nbsp;", ditem.getDeptName()));
//                });
//                resultList.addAll(matchDeptList);
//            }
//
//        });
//        resultList.addAll(noRelationDeptList);
//        return resultList;
//    }

    @Override
    public List<BdDepartment> getDepartmentSourceWithOrganization(BdDepartment entity) {
        List<BdDepartment> resultList = new ArrayList<>();

        if (entity.getDeptCode() != null || entity.getDeptName() != null) {
            //精确查询
            List<BdDepartment> departmentList = baseMapper.getDepartmentSource(entity);
            departmentList.forEach(item->item.setIsRelation(true));
            return baseMapper.getDepartmentSource(entity);
        } else {
            List<BdDepartment> departmentList = baseMapper.getDepartmentSource(entity);
            BdDepartment searchAllEntity = new BdDepartment();
            List<BdDepartment> allDepartmentList = baseMapper.getDepartmentSource(searchAllEntity);
            //拿到所有科室节点
            List<BdDepartment> PDeptList = departmentList.stream().filter(t -> t.getParentCode().equals("1")).collect(Collectors.toList());
            List<BdDepartment> DeptList = departmentList.stream().filter(t -> t.getParentCode().equals("0")).collect(Collectors.toList());

            //获取当前默认的组织关系
            List<BdOrganization> organizationList = getOrganizationRelation(entity);
            List<String> orgDeptCodeList = organizationList.stream().map(t -> t.getDeptCode()).collect(Collectors.toList());
            //未关联部门集合
            List<BdDepartment> noRelationDeptList = DeptList.stream().filter(t -> !orgDeptCodeList.contains(t.getDeptCode())).collect(Collectors.toList());
            noRelationDeptList.forEach(item -> {
                item.setIsRelation(false);
            });
            resultList.addAll(noRelationDeptList);
            PDeptList.forEach(item -> {
                item.setIsRelation(true);
                resultList.add(item);
                List<BdOrganization> matchOrgList = organizationList.stream().filter(t -> t.getPDeptCode().equals(item.getDeptCode())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(matchOrgList)) {
                    List<String> deptCodeList = matchOrgList.stream().map(t -> t.getDeptCode()).collect(Collectors.toList());
                    List<BdDepartment> matchDeptList = allDepartmentList.stream().filter(t -> deptCodeList.contains(t.getDeptCode())).collect(Collectors.toList());
                    matchDeptList.forEach(ditem -> {
                        ditem.setDeptName(String.join("", "&nbsp;&nbsp;&nbsp;", ditem.getDeptName()));
                        ditem.setIsRelation(true);
                    });
                    resultList.addAll(matchDeptList);
                }

            });

            return resultList;
        }
    }

    @Override
    public List<BdDepartment> getDepartmentOrganization(BdDepartment entity) {
        return baseMapper.getDepartmentOrganization(entity);
    }

    @Override
    public List<BdDepartment> getCostDepartments(BdDepartment entity) {
        return baseMapper.getCostDepartments(entity);
    }

    @Override
    public Response addDepartment(BdDepartment entity) {
        try {
            entity.setSysId("COST");
            entity.setSysName("成本系统");
            setEntityValue(entity);
            baseMapper.addDepartment(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "添加失败:", ex.getMessage()));
        }
        return Response.success("添加成功");
    }

    @Override
    public Response modifyDepartment(BdDepartment entity) {
        try {
            //获取默认规则
            BdEnumdetail searchInfo = new BdEnumdetail();
            searchInfo.setEdEdId(1);//院区值
            BdEnumdetail rule = enumdetailService.getDefaultCode(searchInfo);
            if (rule.getEdCode() == null || rule.getEdCode().equals("0")) {
                return Response.error("默认组织架构规则有误,请联系管理员!");
            }
            BdDepartment searchDeptInfo = new BdDepartment();
            searchDeptInfo.setProjectId(entity.getProjectId());
            List<BdDepartment> deptList = getCostDepartments(searchDeptInfo);//获取所有部门

            //数据库记录
            BdDepartment dbRecord = deptList.stream().filter(t -> t.getId().equals(entity.getId())).findFirst().orElse(null);

            //当修改了是否为科室,核算单元时
            if (dbRecord != null && (!dbRecord.getParentCode().equals(entity.getParentCode()) || !dbRecord.getDeptTypeId().equals(entity.getDeptTypeId()))) {
                BdOrganization searchOrgInfo = new BdOrganization();
                searchOrgInfo.setRuleCode(rule.getEdCode());
                searchOrgInfo.setYard(entity.getProjectId());
                searchOrgInfo.setDeptCode(entity.getDeptCode());
//                Boolean retBoolean = organizationService.isHaveOrganization(searchOrgInfo);
//                if (retBoolean) {
//                    return Response.error("科室/部门存在对应关系,不能修改核算单元和是否为科室字段.请先设置对应关系!");
//                }
            }


//            //如果修改的是科室,则去判断该科室是否存在子级部门,在修改核算单元时判断科室和部门是否一致
//            if (entity.getParentCode().equals("1")) {
//                List<BdOrganization> organizationList = getOrganizationRelation(entity);
//                if (CollectionUtils.isNotEmpty(organizationList)) {
//                    List<String> deptCodeList = organizationList.stream().map(t -> t.getDeptCode()).collect(Collectors.toList());
//                    List<BdDepartment> filterDeptList = deptList.stream().filter(t -> deptCodeList.contains(t.getDeptCode())).collect(Collectors.toList());
//
//                    List<String> deptTypeList = filterDeptList.stream().map(t -> t.getDeptTypeId()).collect(Collectors.toList());
//                    deptTypeList.add(entity.getDeptTypeId());
//
//                    if (deptTypeList.stream().distinct().count() > 1) {
//                        return Response.error("与科室下子部门核算单元不一致,请先修改子部门核算单元");
//                    }
//                }
//            } else {
//
//            }

            setEntityValue(entity);
            baseMapper.modifyDepartment(entity);
        } catch (Exception ex) {
            return Response.error(String.join(":", "修改失败:", ex.getMessage()));
        }
        Response ret = new Response();
        ret.setMessage("修改成功");
        return ret;

    }

    @Override
    public boolean updateRowStatusById(Integer id,String rowStatus)
    {
        LambdaUpdateWrapper<BdDepartment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BdDepartment::getId, id)
                .set(BdDepartment::getRowStatus, rowStatus);
        int update = baseMapper.update(new BdDepartment(), updateWrapper);
        return update >0;
    }

    @Override
    public boolean deleteById(Integer id) {
        return baseMapper.deleteById(id)>0;
    }

    @Override
    public String getMaxDeptCode(BdDepartment entity) {
        return baseMapper.getMaxDeptCode(entity);
    }

    @Override
    public BdDepartmentVO getCostDepartment() {
        BdDepartmentVO bdDepartmentVO = new BdDepartmentVO();
        bdDepartmentVO.setDeptCode("0000");
        bdDepartmentVO.setDeptName("全部");
        List<BdSysUserDeptCodeVO>  list=new ArrayList<>();
        list.addAll(baseMapper.getCostDepartment());
        list.addAll(baseMapper.getCostDepartmentXG());
        bdDepartmentVO.setChildrens(list);
        return bdDepartmentVO;
    }

    private void setEntityValue(BdDepartment entity) {
        Date currDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:hh:ss");
        entity.setCreatedOn(sdf.format(currDate));
        entity.setUpdatedOn(sdf.format(currDate));
        String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
        userName = userName == null || userName.isEmpty() ? "System" : userName;
        entity.setCreatedBy(userName);
        entity.setUpdatedBy(userName);
    }

    /**
     * 根据科室编号获取部门关系
     *
     * @param entity
     * @return
     */
    public List<BdOrganization> getOrganizationRelation(BdDepartment entity) {
        //获取默认规则
        BdEnumdetail searchInfo = new BdEnumdetail();
        searchInfo.setEdEdId(1);//院区值
        BdEnumdetail rule = enumdetailService.getDefaultCode(searchInfo);
        BdOrganization searchOrganzationInfo = new BdOrganization();
        searchOrganzationInfo.setRuleCode(rule.getEdCode());
        searchOrganzationInfo.setYard(entity.getProjectId());
        searchOrganzationInfo.setPDeptCode(entity.getDeptCode());
        searchOrganzationInfo.setRowStatus("0");
        return organizationService.getOrganizationNormal(searchOrganzationInfo);
    }






}
